package com.winning.pmph.ctrl;

import com.alibaba.druid.util.Base64;
import com.winning.pmph.entity.UncommonWord;
import com.winning.pmph.service.UncommonWordService;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

@Api(value = "知识工具管理/生僻字管理")
@RestController
@RequestMapping("/pmph/action/UncommonWordCtrl")
public class UncommonWordCtrl {

    @Resource
    private UncommonWordService uncommonWordService;

    @ApiOperation(value = "selectAll", notes = "查询生僻字列表")
    @GetMapping("/selectAll")
    public List<UncommonWord> selectAll() {
        return uncommonWordService.list();
    }

    @ApiOperation(value = "uploadUncommonWord", notes = "上传生僻字接口")
    @PostMapping("/uploadUncommonWord")
    public UncommonWord uploadUncommonWord(MultipartFile file) {
        UncommonWord uncommonWord = new UncommonWord();
        String storedName = UploadFileUtil.uploadFile(file, ApplicationContextUtil.BASE_DOWN_FORDER + "image/bz/");
        uncommonWord.setPath("/ymer/action/file/showImage?filename=image/bz/" + storedName);
        return uncommonWord;
    }

    @ApiOperation(value = "saveUncommonWord", notes = "保存生僻字接口")
    @PostMapping("/saveUncommonWord")
    public void saveUncommonWord(@RequestBody UncommonWord uncommonWord) throws IOException {
        // 根据path找filename;
        String srcFileName = uncommonWord.getPath().substring(uncommonWord.getPath().lastIndexOf("/") + 1);
        String destFileName = uncommonWord.getId() + srcFileName.substring(srcFileName.lastIndexOf("."));
        if (!Objects.equals(srcFileName, destFileName)) {
            File srcFile = new File(ApplicationContextUtil.BASE_DOWN_FORDER + "image/bz/" + srcFileName);
            File destFile = new File(ApplicationContextUtil.BASE_DOWN_FORDER + "image/bz/" + destFileName);
            FileUtils.copyFile(srcFile, destFile);
            srcFile.delete();
            uncommonWord.setPath("/ymer/action/file/showImage?filename=image/bz/" + destFileName);
            uncommonWord.setContent("data:image/" + uncommonWord.getContentType() + ";base64," + Base64.byteArrayToBase64(FileUtils.readFileToByteArray(destFile)));
        }
        uncommonWordService.saveOrUpdate(uncommonWord);
    }

    @ApiOperation(value = "deleteUncommonWordById", notes = "删除生僻字接口")
    @PostMapping("/deleteUncommonWordById")
    public void deleteUncommonWordById(String id) {
        uncommonWordService.removeById(id);
    }
}
